/**
* author: huangjianhong
* date: 2024
* description:
**/
<template>
  <div class="flex-box course-detail">
    <div class="detail-tree pt-15 h-100 mr-15">
      <div class="mb-15 flex-box-justify-space-between">
        <el-button type="primary" icon="el-icon-plus" size="small" @click="addCatalogue('peer')" :disabled="!this.treeData.length">同级目录</el-button>
        <el-button type="primary" icon="el-icon-plus" size="small" @click="addCatalogue('child')" :disabled="childBtnDisabled">子目录</el-button>
      </div>
      <div class="overview-text mb-15 can-click" @click="clickOverView()" :class="{'active': overviewActive}">
        <span>课程总览</span>
        <span>
          <svg-icon @click.stop="editCatalogue()" icon-class="note" class="can-click" />
          <svg-icon @click.stop="delCatalogue()" icon-class="delete" class="can-click" />
        </span>
      </div>
      <el-tree class="i-tree course-detail-tree"
               :highlight-current="highlightCurrent"
               :data="treeData"
               :props="defaultProps"
               v-loading="treeLoading"
               default-expand-all
               @node-click="nodeClick">
      </el-tree>
    </div>
    <div class="detail-wrap formBox2">
      <div v-show="overviewShow">
        <div class="course-list-text">基础信息</div>
        <el-form
          :model="formData"
          :rules="formRules"
          inline
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <div>
            <el-form-item label="课程封面" prop="courseImgUrl">
              <el-upload
                v-loading="imgLoading"
                class="avatar-uploader"
                action=""
                :show-file-list="false"
                :http-request="uploadImage"
                :before-upload="overImgBefore"
              >
                <video class="upload-video" v-if="suffix === 'mp4' && formData.courseImgUrl" :src="formData.courseImgUrl"></video>
                <img v-else-if="suffix !== 'mp4' && formData.courseImgUrl" :src="formData.courseImgUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <i v-if="formData.courseImgUrl" class="el-icon-remove" @click.stop="formData.courseImgUrl=''"></i>
                <el-progress v-if="coverPercentageShow" type="circle" :percentage="coverPercentage" :width="108"></el-progress>
              </el-upload>
            </el-form-item>
          </div>
          <el-form-item label="课程名称" prop="courseTitle">
            <el-input
              style="width: 323px"
              v-model="formData.courseTitle"
              placeholder="请输入课程名称"
              maxlength="60"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="课程分类" prop="courseTypeId">
            <el-select
              v-model="formData.courseTypeId"
              placeholder="请选择分类"
              clearable
              style="width: 389px"
            >
              <el-option
                v-for="item in classificationSelect"
                :key="item.id"
                :label="item.courseType"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <div>
            <el-form-item label="课程简介" prop="courseIntroduction">
              <el-input
                type="textarea"
                :rows="5"
                v-model="formData.courseIntroduction"
                placeholder="请输入课程简介"
                maxlength="400"
                style="width: 800px"
                show-word-limit
              />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="课程介绍" prop="courseContent">
              <div id="wangEditor" class="i-wangEditor"></div>
              <!--<vueUeditorWrap-->
                <!--v-model="formData.courseContent"-->
                <!--:config="myConfig"-->
                <!--:key="1"-->
                <!--class="lh-0"-->
              <!--&gt;</vueUeditorWrap>-->
            </el-form-item>
          </div>
          <div style="text-align: center;padding:20px 0">
            <el-button type @click="goBack">返回</el-button>
            <el-button type="primary" @click="submitForm" :loading="isSaveLoading">确定</el-button>
          </div>
        </el-form>
      </div>
      <div v-show="!overviewShow">
        <div class="course-list-text">课程信息</div>
        <div class="mb-20">
          <el-button size="small" plain type="primary" icon="el-icon-plus" @click="addContent()">添加内容</el-button>
          <el-button size="small" :disabled="importDisabled" plain type="primary" @click="importFrame()">引入上节框架</el-button>
        </div>
        <div v-for="(item, index) in contentList" :key="index" class="content-list" v-loading="contentLoading">
          <!--文档-->
          <div v-if="item.fileType === 1">
            <div class="content-item">
              <div class="btnS">
                <span class="type mb-15 mr-30">{{ item.contentName }}</span>
                <el-tooltip content="删除" placement="top"><svg-icon icon-class="delete" @click="delPDFOrVideo(item, index)" /></el-tooltip>
              </div>
              <el-upload
                class="avatar-uploader"
                action=""
                :show-file-list="false"
                :http-request="(params) => uploadImgOrAnnex(params, item, index)"
                :before-upload="(params) => beforeUpload(params, item, index)"
                v-loading="item.loading"
              >
                <img v-if="item.contentUlrArr && item.contentUlrArr.length" :src="item.fileType === 1 ? imgPDF : imgVideo" class="avatar" />
                <i v-if="item.contentUlrArr && item.contentUlrArr.length" class="el-icon-remove" @click.stop="item.contentUlrArr = []"></i>
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <el-progress v-if="item.percentageShow" type="circle" :percentage="item.percentage" :width="108"></el-progress>
              </el-upload>
              <span class="content-file-name">{{ (item.contentUlrArr && item.contentUlrArr[0] && item.contentUlrArr[0].fileName) ? item.contentUlrArr[0].fileName : '' }}</span>
            </div>
          </div>
          <!--视频-->
          <div v-if="item.fileType === 2" class="flex-box">
            <div class="content-item" :class="{'active': item.fileType === 2}">
              <div class="btnS">
                <span class="type mb-15 mr-30">{{ item.contentName }}</span>
                <el-tooltip content="删除" placement="top"><svg-icon icon-class="delete" @click="delPDFOrVideo(item, index)" /></el-tooltip>
              </div>
              <div class="content-img-list flex-box">
                <div class="content-item-wrap" v-for="(ite, n) in item.contentUlrArr" :key="`item-${n}`">
                  <img :src="imgVideo" class="avatar" />
                  <i class="el-icon-remove" @click="reduceImgOrAnnex(item, ite, n)"></i>
                  <span class="file-img-name">{{ (ite && ite.fileName) ? ite.fileName : '' }}</span>
                </div>
                <!--<div class="avatar-uploader" @click="uploadVideo()"><i class="el-icon-plus avatar-uploader-icon"></i></div>-->
                <el-upload
                  class="avatar-uploader"
                  action=""
                  :show-file-list="false"
                  :http-request="(params) => uploadImgOrAnnex(params, item, index)"
                  :before-upload="(params) => beforeUpload(params, item, index)"
                  v-loading="item.loading"
                >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <el-progress v-if="item.percentageShow" type="circle" :percentage="item.percentage" :width="108"></el-progress>
                </el-upload>
              </div>
            </div>
          </div>
          <!--图片、附件-->
          <div v-if="item.fileType === 3 || item.fileType === 4" class="flex-box">
            <div class="content-item" :class="{'active': item.fileType === 3 || item.fileType === 4}">
              <div class="btnS">
                <span class="type mb-15 mr-30">{{ item.contentName }}</span>
                <el-tooltip content="删除" placement="top"><svg-icon icon-class="delete" @click="delPDFOrVideo(item, index)" /></el-tooltip>
              </div>
              <div class="content-img-list flex-box">
                <div class="content-item-wrap" v-for="(ite, n) in item.contentUlrArr" :key="`item-${n}`">
                  <img :src="item.fileType === 3 ? ite.fileUrl : (item.fileType === 2 ? imgVideo : imgAnnex)" class="avatar" />
                  <i class="el-icon-remove" @click="reduceImgOrAnnex(item, ite, n)"></i>
                  <span class="file-img-name">{{ (ite && ite.fileName) ? ite.fileName : '' }}</span>
                </div>
                <el-upload
                  class="avatar-uploader"
                  action=""
                  :show-file-list="false"
                  :http-request="(params) => uploadImgOrAnnex(params, item, index)"
                  :before-upload="(params) => beforeUpload(params, item, index)"
                  v-loading="item.loading"
                >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <el-progress v-if="item.percentageShow" type="circle" :percentage="item.percentage" :width="108"></el-progress>
                </el-upload>
              </div>
            </div>
          </div>
        </div>
        <div><el-button type="primary" size="small" @click="updateCourse()" :disabled="saveBtnDisabled">保存</el-button></div>
      </div>
    </div>
    <!--添加目录弹窗-->
    <form-wrap :title="catalogueTitle" ref="catalogueDialog" @submit="submit"></form-wrap>
    <form-wrap title="目录名称编辑" ref="editCatalogueDialog" @submit="sureEdit"></form-wrap>
    <!--添加内容弹窗-->
    <el-dialog :visible.sync="contentDialog" width="550px" custom-class="input-dialog" @close="closeContentDialog" title="输入内容信息">
      <el-form label-width="120px" :model="contentForm" :rules="contentRules" ref="contentForm">
        <el-form-item label="内容名称：" prop="contentName">
          <el-input size="small" v-model="contentForm.contentName" placeholder="请输入内容名称"></el-input>
        </el-form-item>
        <el-form-item label="文件类型：" prop="fileType">
          <span class="content-tab-btn can-click mr-15"
                v-for="(item, i) in fileTypeTabs"
                :key="i"
                :class="{'active': item.active}"
                @click="chooseContentType(item)"
          >{{ item.name }}</span>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="small" type="primary" @click="sureAddContent()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="uploadVideoDialog" width="850px" custom-class="input-dialog" @close="closeVideoDialog" title="视频上传" :show-close="false">
      <div class="formBox2">
        <el-upload
          class=""
          multiple
          action=""
          list-type="picture-card"
          :http-request="(params) => uploadVideoFun(params)"
          :before-upload="(params) => beforeUploadVideo(params)"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
          <!--<el-progress v-if="percentageShow" type="circle" :percentage="percentage" :width="108"></el-progress>-->
        </el-upload>
      </div>
      <span slot="footer">
        <el-button size="small">关闭页面</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  const OSS = require('ali-oss');
  import formWrap from '@/components/form'
  import imgPDF from '@/assets/images/img_PDF.jpeg'
  import imgVideo from '@/assets/images/img_video.jpeg'
  import imgAnnex from '@/assets/images/img_annex.jpeg'
  import _ from 'lodash'
  export default {
    name: 'courseDetail',
    components: { formWrap },
    data(){
      let query = this.$route.query;
      return {
        query,
        imgPDF: imgPDF,
        imgVideo: imgVideo,
        imgAnnex: imgAnnex,
        treeLoading: false,
        courseId: '',
        treeData: [],
        defaultProps: {
          label: 'chapterName',
          children: 'children'
        },
        headers: {},
        action: '',
        formData: {
          courseImgUrl: '', // 封面
          courseTitle: '', // 课程名称
          courseTypeId: '', // 课程分类
          courseIntroduction: '', // 课程简介
          courseContent: '', // 课程介绍
        },
        suffix: '', // 封面格式
        formRules: {},
        myConfig: {
          autoHeightEnabled: false,
          initialFrameHeight: 500,
          initialFrameWidth: 800,
          UEDITOR_HOME_URL: '/UEditor/',
          serverUrl: process.env.VUE_APP_BASE_API + 'enterprise/ueditorUpload'
        },
        classificationSelect: [], // 课程分类列表
        isSaveLoading: false,
        imgLoading: false, // 图片loading
        childBtnDisabled: false,
        catalogueTitle: '',
        chooseNodeData: null, // 选中的树形节点（章节）
        chooseNode: null,
        overviewActive: true,
        overviewShow: true, // 显示课程总览详情
        contentForm: {
          contentName: '', // 添加内容弹窗——文件名称
        },
        fileTypeTabs: [
          { name: '文档', type: 1, active: true },
          { name: '视频', type: 2, active: false },
          { name: '图片', type: 3, active: false },
          { name: '附件', type: 4, active: false },
        ], // 添加内容弹窗——类型
        contentDialog: false, // 添加内容弹窗
        contentRules: {
          contentName: { required: true, message: '请输入内容名称', trigger: 'blur' }
        },
        contentList: [], // 课程内容列表
        contentLoading: false,
        fileType: null,
        highlightCurrent: false,
        saveBtnDisabled: false,
        editor: null,
        sizeDivision: 1024 * 1024 * 3,
        importDisabled: true, // ‘引入上节框架’按钮置灰与否
        treeIndex: 0,
        parentChildNodes: [],
        uploadVideoDialog: false, // 视频上传弹窗
        percentageShow: true,
        percentage: 0,
        coverPercentageShow: false,
        coverPercentage: 0,
      }
    },
    created() {
      if(this.query && this.query.courseId){
        this.courseId = this.query.courseId;
        // 课程树
        this.getTree();
        // 课程详情
        this.getDetail();
      }
      // 课程分类
      this.getCourseClass();
    },
    mounted(){
      this.editor = new this.wangEditor('#wangEditor');
      this.editor.config.customUploadImg = this.editorUploadImg;
      this.editor.create();
    },
    methods: {
      getTree(){
        this.treeLoading = true;
        let param = {
          courseOverviewId: this.courseId
        };
        this.$api.course.courseTree(param).then(res => {
          this.treeData = res.data || [];
          this.treeLoading = false;
        });
      },
      getDetail(){
        let param = {
          id: this.courseId
        };
        this.$api.course.courseDetail(param).then(res => {
          this.formData = res.data || {};
          if(this.formData.courseImgUrl){
            this.suffix = this.getFileExtension(this.formData.courseImgUrl);
          }
          // 富文本编辑器设置内容
          this.editor.txt.html(this.formData.courseContent);
        });
      },
      getCourseClass(){
        let param = {
          currentPage: 1,
          pageSize: 999
        };
        this.$api.course.courseClassification(param).then(res => {
          this.classificationSelect = res.data || [];
        });
      },
      getUploadToken(){
        let promise = new Promise((resolve, reject)=>{
          let param = {};
          this.$api.course.getOssAccessInfo(param).then(res => {
            const client = new OSS({
              // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
              region: 'oss-cn-beijing',
              // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
              accessKeyId: res.data.accessKeyId,
              accessKeySecret: res.data.accessKeySecret,
              // 从STS服务获取的安全令牌（SecurityToken）。
              stsToken: res.data.securityToken,
              retryMax: 3, // 需指定retryMax，否则refreshSTSToken无法执行
              refreshSTSToken: async () => {
                // 向您搭建的STS服务获取临时访问凭证。
                let url = process.env.VUE_APP_BASE_API + 'oss/getOssAccessInfo'
                const info = await fetch(url);
                return {
                  accessKeyId: info.accessKeyId,
                  accessKeySecret: info.accessKeySecret,
                  stsToken: info.securityToken
                }
              },
              // 刷新临时访问凭证的时间间隔，单位为毫秒。
              refreshSTSTokenInterval: 300000,
              // 填写Bucket名称。
              bucket: 'ds-course'
            });
            return resolve(client);
          }).catch((err)=>{
            return reject(err)
          });
        })
        return promise;
      },
      uploadImage(file){
        this.getUploadToken().then((client)=>{
          let fileName = file.file.name;
          let fileSize = file.file.size;
          let that = this;

          if(fileSize >= this.sizeDivision){
            const options = {
              // 获取分片上传进度、断点和返回值。
              progress: (p, cpt, res) => {
                that.coverPercentage = Number((p * 100).toFixed(0));
                that.$forceUpdate();
              },
              // 设置并发上传的分片数量。
              parallel: 9999,
              // 设置分片大小。默认值为1 MB，最小值为100 KB。
              partSize: 1024 * 512,
              timeout: 86400000,//设置超时时间
              // headers,
              // 自定义元数据，通过HeadObject接口可以获取Object的元数据。
              meta: { year: 2020, people: "dev" },
            };
            async function multipartUpload() {
              try {
                let result = await client.multipartUpload(
                  fileName,
                  file.file,
                  {
                    ...options,
                  }
                );

                let head = await client.head(fileName);
                that.coverPercentageShow = false;
                that.formData.courseImgUrl = head.res.requestUrls[0];
                that.suffix = that.getFileExtension(head.res.requestUrls[0]);
                that.$forceUpdate();
              } catch (e) {
                // 捕获超时异常。
                console.error('err', e);
              }
            }
            multipartUpload();
          }else {
            client.put(fileName, file.file).then((res)=>{
              this.imgLoading = false;
              this.formData.courseImgUrl = res.url;
              this.suffix = this.getFileExtension(this.formData.courseImgUrl);
            }).catch(function (err) {
              this.imgLoading = false;
              this.$message.error(err);
            });
          }
        }).catch(()=>{})
      },
      overImgBefore(file){
        // this.imgLoading = true;
        // 文件大小超过3M，就用进度条；否则用普通loading
        if(file.size >= this.sizeDivision){
          this.coverPercentageShow = true;
        }else {
          this.imgLoading = true;
        }
        this.$forceUpdate();
      },
      goBack(){
        this.$router.go(-1)
      },
      submitForm(){
        if(this.query && this.query.type && this.query.type === 'edit'){
          let param = {
            id: this.courseId, // 课程id
            courseTitle: this.formData.courseTitle, // 课程名称
            courseTypeId: this.formData.courseTypeId, // 课程分类id
            courseImgUrl: this.formData.courseImgUrl, // 课程照片
            courseIntroduction: this.formData.courseIntroduction, // 课程简介
            courseContent: this.editor.txt.html(), // 课程内容介绍
            // courseContent: this.formData.courseContent, // 课程内容介绍
          };
          this.$api.course.courseUpdate(param).then(res => {
            if(res.status.code === 200){
              this.$message.success('编辑成功')
            }
          });
        }else {

        }
      },
      /**
      * 树形点击
      **/
      nodeClick(data, node, val){
        // 设置‘引入上节框架’按钮disabled
        this.parentChildNodes = node.parent.childNodes; // 当前层级所有数据
        if(this.parentChildNodes.length === 1 || (node.id === this.parentChildNodes[0].id)){
          this.importDisabled = true;
        }else {
          this.importDisabled = false;
        }
        this.treeIndex = _.findIndex(this.parentChildNodes, function(o) { return o.id === node.id; });
        // 点击事件处理、获取章节详情
        this.chooseNodeData = data;
        this.chooseNode = node;
        this.highlightCurrent = true;
        if(node.level === 2){
          this.overviewShow = false; // 显示课程总览详情
          this.overviewActive = false; // ‘课程总览’按钮active
          // 获取课程章节详情
          this.getCourseChapterInfo(data);
        }
        if(node.level === 3){
          this.childBtnDisabled = true; // 添加子目录按钮
          this.overviewShow = false; // 显示课程总览详情
          this.overviewActive = false; // ‘课程总览’按钮active
          // 获取课程章节详情
          this.getCourseChapterInfo(data);
        }else {
          this.childBtnDisabled = false;
        }
      },
      /**
      * 获取课程章节详情
      **/
      getCourseChapterInfo(data){
        this.contentLoading = true;
        let param = {
          courseOverviewId: this.courseId,
          courseChapterId: data.id,
        };
        this.$api.course.courseChapterInfo(param).then(res => {
          this.contentLoading = false;
          this.contentList = res.data || [];
          if(this.contentList.length){
            this.contentList.forEach((item)=>{
              if(item.contentUlr !== ''){
                this.$set(item, 'contentUlrArr', JSON.parse(item.contentUlr))
              }else {
                this.$set(item, 'contentUlrArr', [])
              }
            })
          }
        })
      },
      /**
       * 添加同级目录/子目录
       **/
      addCatalogue(type){
        let labelList = [
          { label: '目录名称', prop: 'chapterName', type: 'input', required: true }
        ];
        if(!this.treeData.length){
          this.$refs.catalogueDialog.showDialog(labelList);
          return;
        }
        if(type === 'child' && this.chooseNode.level === 2 && this.contentList.length){
          this.$message.warning('该层级存在资源，暂不支持添加子目录');
          return;
        }
        if(!this.chooseNodeData){
          this.$message.warning('请选择节点');
          return;
        }
        if(type === 'peer'){
          this.catalogueTitle = '同级目录';
        }else {
          this.catalogueTitle = '子目录';
        }
        // 打开添加目录的弹窗
        this.$refs.catalogueDialog.showDialog(labelList);
      },
      /**
       * 添加同级目录/子目录——确定
       **/
      submit(form){
        let param = {
          courseOverviewId: this.courseId,
          parentsId: !this.treeData.length ? 0 : (this.catalogueTitle === '子目录' ? this.chooseNodeData.id : this.chooseNodeData.parentsId), // 父级id
          chapterName: form.chapterName,
          hierarchy: !this.treeData.length ? 1 : (this.catalogueTitle === '子目录' ? this.chooseNode.level + 1 : this.chooseNode.level), // 层级
        };
        this.$api.course.courseChapterAdd(param).then(res => {
          if(res.status.code === 200){
            this.$message.success('新增成功');
            this.$refs.catalogueDialog.cancel();
            this.getTree();
          }
        });
      },
      /**
       * 打开目录名称编辑弹窗
       **/
      editCatalogue(){
        if(!this.chooseNodeData){
          this.$message.warning('请选择节点');
          return
        }
        let labelList = [
          { label: '目录名称', prop: 'chapterName', type: 'input', required: true }
        ];
        let form = {
          chapterName: this.chooseNodeData.chapterName
        };
        this.$refs.editCatalogueDialog.showForm(form, labelList)
      },
      /**
       * 目录删除
       **/
      delCatalogue(){
        if(!this.chooseNodeData){
          this.$message.warning('请选择节点');
          return
        }
        // 树形第1层
        if(this.chooseNode.level === 1){
          if(this.chooseNodeData.children.length){
            this.$message.warning('此章节底下有子目录，不能删除！');
            return
          }else {
            this.delNode();
          }
        }
        // 树形第2层
        if(this.chooseNode.level === 2){
          if(this.chooseNodeData.children.length){
            this.$message.warning('此章节底下有子目录，不能删除！');
            return
          }else if(!this.chooseNodeData.children.length) {
            this.getNodeDetail();
          }else {
            this.delNode();
          }
        }
        // 树形第3层
        if(this.chooseNode.level === 3){
          this.getNodeDetail();
        }
      },
      delNode(){
        this.$confirm(`确定要删除"${this.chooseNodeData.chapterName}"这个章节吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = {
            id: this.chooseNodeData.id
          };
          this.$api.course.courseChapterDel(param).then(res => {
            if(res.status.code === 200){
              this.$message.success('删除成功');
              this.getTree();
            }
          });
        }).catch(() => {});
      },
      getNodeDetail(){
        let param = {
          courseOverviewId: this.courseId,
          courseChapterId: this.chooseNodeData.id,
        };
        this.$api.course.courseChapterInfo(param).then(res => {
          if(res.data.length){
            this.$message.warning('此章节底下有课程，不能删除！');
          }else {
            this.$confirm(`确定要删除"${this.chooseNodeData.chapterName}"这个章节吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let param = {
                id: this.chooseNodeData.id
              };
              this.$api.course.courseChapterDel(param).then(res => {
                if(res.status.code === 200){
                  this.$message.success('删除成功');
                  this.getTree();
                }
              });
            }).catch(() => {});
          }
        });
      },
      /**
       * 点击课程总览
       **/
      clickOverView(){
        this.overviewActive = true;
        this.overviewShow = true;
        this.chooseNodeData = null;
        this.highlightCurrent = false;
      },
      /**
       * 添加目录编辑
       **/
      sureEdit(form){
        let param = {
          id: this.chooseNodeData.id,
          courseOverviewId: this.courseId,
          parentsId: this.chooseNodeData.parentsId, // 父级id
          chapterName: form.chapterName,
          hierarchy: this.chooseNode.level, // 层级
        };
        this.$api.course.courseChapterEdit(param).then(res => {
          if(res.status.code === 200){
            this.$message.success('编辑成功');
            this.$refs.editCatalogueDialog.cancel();
            this.getTree();
          }
        });
      },
      /**
       * 打开添加内容弹窗
       **/
      addContent(){
        if(this.chooseNode.level === 2 && this.chooseNodeData.children.length){
          this.$message.warning('该层级存在子目录，暂不支持添加资源');
          return;
        }
        this.contentDialog = true;
      },
      /**
       * 引入上节框架
       **/
      importFrame(){
        this.$confirm(`请确认是否引入上一节框架?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 获取上节框架
          let param = {
            courseOverviewId: this.courseId,
            courseChapterId: this.parentChildNodes[this.treeIndex - 1].data.id,
          };
          this.$api.course.courseChapterInfo(param).then(res => {
            let data = res.data;
            this.contentList = data.map(item => ({ contentName: item.contentName, fileType: item.fileType }));
          })
        }).catch(() => {});
      },
      /**
       * 关闭添加内容弹窗回调
       **/
      closeContentDialog(){},
      /**
       * 添加内容弹窗——选择文件类型
       **/
      chooseContentType(item){
        for(let item of this.fileTypeTabs){
          item.active = false
        }
        item.active = true;
        this.fileType = item.type;
      },
      /**
       * 添加内容弹窗——确定
       **/
      sureAddContent(){
        this.$refs['contentForm'].validate((valid) => {
          if (valid) {
            let obj = {
              contentName: this.contentForm.contentName,
              fileType: this.fileType ? this.fileType : 1,
            };
            this.contentDialog = false;
            this.contentList.push(obj);
          }
        })
      },
      /**
       * 添加内容——图片或附件
       **/
      uploadImgOrAnnex(file, item, i){
        this.getUploadToken().then((client)=>{
          let fileName = file.file.name;
          let fileSize = file.file.size;
          let that = this;
          if(fileSize >= this.sizeDivision){
            const options = {
              // 获取分片上传进度、断点和返回值。
              progress: (p, cpt, res) => {
                // that.uploadId = cpt.uploadId;//取消时需要的参数
                // that.progress = Number((p * 100).toFixed(0));//进度条
                that.contentList[i].percentage = Number((p * 100).toFixed(0));
                that.$forceUpdate();
              },
              // 设置并发上传的分片数量。
              parallel: 9999,
              // 设置分片大小。默认值为1 MB，最小值为100 KB。
              partSize: 1024 * 1024 * 2,
              timeout: 86400000,//设置超时时间
              // headers,
              // 自定义元数据，通过HeadObject接口可以获取Object的元数据。
              meta: { year: 2020, people: "dev" },
            };
            async function multipartUpload() {
              try {
                let result = await client.multipartUpload(
                  fileName,
                  file.file,
                  {
                    ...options,
                  }
                );
                let head = await client.head(fileName);
                that.contentList[i].percentageShow = false;
                that.$forceUpdate();
                let suffix = that.getFileExtension(head.res.requestUrls[0]); // 后缀名
                // 设置要显示的obj
                if(that.contentList[i] && that.contentList[i].contentUlrArr){
                  that.contentList[i].contentUlrArr.push({
                    fileUrl: head.res.requestUrls[0],
                    fileName: result.name,
                    fileSuffix: '.' + suffix,
                  })
                }else {
                  that.$set(that.contentList[i], 'contentUlrArr', [{
                    fileUrl: head.res.requestUrls[0],
                    fileName: result.name,
                    fileSuffix: '.' + suffix,
                  }])
                }
              } catch (e) {
                // 捕获超时异常。
                console.error('err', e);
              }
            }
            multipartUpload();
          }else {
            client.put(fileName, file.file).then((res)=>{
              this.contentList[i].loading = false;
              let suffix = this.getFileExtension(res.url); // 后缀名
              // 设置要显示的obj
              if(this.contentList[i] && this.contentList[i].contentUlrArr){
                this.contentList[i].contentUlrArr.push({
                  fileUrl: res.url,
                  fileName: res.name,
                  fileSuffix: '.' + suffix,
                })
              }else {
                this.$set(this.contentList[i], 'contentUlrArr', [{
                  fileUrl: res.url,
                  fileName: res.name,
                  fileSuffix: '.' + suffix,
                }])
              }
            })
          }
        });
      },
      beforeUpload(file, item, i){
        // 文件大小超过3M，就用进度条；否则用普通loading
        if(file.size >= this.sizeDivision){
          this.contentList[i].percentageShow = true;
        }else {
          this.contentList[i].loading = true;
        }
        this.$forceUpdate();
      },
      /**
       * 添加内容——获取文件后缀名
       **/
      getFileExtension(filename) {
        // 使用split分割字符串，并取得最后一个元素（后缀名）
        const extension = filename.split('.').pop();
        // 返回后缀名，如果不存在则返回空字符串
        return extension || '';
      },
      reduceImgOrAnnex(item, ite, n){
        item.contentUlrArr.splice(n, 1)
      },
      /**
       * 添加内容——删除PDF或视频
       **/
      delPDFOrVideo(item, index){
        this.$confirm(`确定要删除吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(item.id){
            let param = {
              id: item.id
            };
            this.$api.course.courseListDel(param).then(res => {
              if(res.status.code === 200){
                this.$message.success('删除成功');
                this.getCourseChapterInfo(this.chooseNodeData);
              }
            });
          }else {
            this.$message.success('删除成功');
            this.contentList.splice(index, 1);
          }
        }).catch(() => {});
      },
      /**
       * 添加内容——批量保存
       **/
      updateCourse(){
        if(this.chooseNode.level === 2 && this.chooseNodeData.children.length){
          this.$message.warning('该层级存在子目录，暂不支持添加资源');
          return;
        }
        if(this.contentList.length){
          this.contentList.forEach((item)=>{
            if(item.contentUlrArr && item.contentUlrArr.length){
              this.$set(item, 'contentUlr', JSON.stringify(item.contentUlrArr))
            }else {
              this.$set(item, 'contentUlr', '')
            }
          })
        }
        let haveNewAdd = 1; // 1：只有编辑；2：有编辑有新增；3：只有新增
        let arr1 = []; // 原本存在的数组
        this.contentList.forEach((item)=>{
          if(item.id){
            arr1.push(item)
          }
        })
        if(arr1.length === this.contentList.length){
          haveNewAdd = 1
        }else if(arr1.length < this.contentList.length && arr1.length > 0){
          haveNewAdd = 2
        }else {
          haveNewAdd = 3
        }
        if(haveNewAdd === 1){
          // 编辑
          let list = this.contentList.map((item)=>{
            return {
              id: item.id ? item.id : '',
              courseOverviewId: item.courseOverviewId,
              courseChapterId: item.courseChapterId,
              contentName: item.contentName,
              contentUlr: item.contentUlr,
              fileType: item.fileType,
            }
          });
          let param = {
            list: list
          };
          this.$api.course.courseDetailUpdate(param).then((res)=>{
            if(res.status.code === 200){
              this.$message.success('保存成功')
            }
          })
        }else if(haveNewAdd === 2){
          // 编辑
          let list = this.contentList.map((item)=>{
            return {
              id: item.id ? item.id : '',
              courseOverviewId: item.courseOverviewId,
              courseChapterId: item.courseChapterId,
              contentName: item.contentName,
              contentUlr: item.contentUlr,
              fileType: item.fileType,
            }
          });
          let param = {
            list: list
          };
          this.$api.course.courseDetailUpdate(param).then((res)=>{
            if(res.status.code === 200){
              this.$message.success('保存成功')
            }
          })
          // 新增
          let contentListAdd = [];
          this.contentList.forEach((item)=>{
            if(!item.id){
              contentListAdd.push({
                courseOverviewId: this.courseId,
                courseChapterId: this.chooseNodeData.id,
                contentName: item.contentName,
                contentUlr: item.contentUlr,
                fileType: item.fileType,
              })
            }
          });
          let param1 = {
            list: contentListAdd
          };
          this.$api.course.courseDetailAdd(param1).then((res)=>{
            this.getCourseChapterInfo(this.chooseNodeData);
          })
        }else {
          // 新增
          let contentListAdd = [];
          this.contentList.forEach((item)=>{
            if(!item.id){
              contentListAdd.push({
                courseOverviewId: this.courseId,
                courseChapterId: this.chooseNodeData.id,
                contentName: item.contentName,
                contentUlr: item.contentUlr,
                fileType: item.fileType,
              })
            }
          });
          let param = {
            list: contentListAdd
          };
          this.$api.course.courseDetailAdd(param).then((res)=>{
            if(res.status.code === 200){
              this.$message.success('保存成功')
            }
            this.getCourseChapterInfo(this.chooseNodeData);
          })
        }
      },
      editorUploadImg(file, insert){
        this.getUploadToken().then((client)=>{
          let fileName = file[0].name;
          client.put(fileName, file[0]).then(function (result) {
            insert(result.res.requestUrls[0])
          }).catch(()=>{});
        });
      },
      uploadVideo(){
        this.uploadVideoDialog = true;
      },
      closeVideoDialog(){},
      uploadVideoFun(file){
        console.log(333, file)
      },
      beforeUploadVideo(file){},
    }
  }
</script>

<style scoped lang="scss">
  @import "../../styles/modules/course";
</style>
